package com.example.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.api.ApiResult;
import com.example.entity.emp.SysUser;
import com.example.service.CaptchaService;
import com.example.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService userService;
    private final CaptchaService captchaService;

    /**
     * 登录参数接收类
     */
    @Data
    public static class LoginRequest {
        private String username;
        private String password;
        private String captcha;
        private String captchaId;
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ApiResult<String> login(@RequestBody LoginRequest loginRequest) {
        // 验证验证码
        boolean captchaValid = captchaService.verifyCaptcha(
            loginRequest.getCaptchaId(), loginRequest.getCaptcha());
        if (!captchaValid) {
            return ApiResult.validateFailed("验证码不正确或已过期");
        }
        
        // 验证用户名和密码
        String token = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
        return ApiResult.success(token);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ApiResult<Void> register(@Validated @RequestBody SysUser user) {
        userService.register(user);
        return ApiResult.success();
    }

    @GetMapping("/info")
    @ApiOperation("获取当前用户信息")
    @SaCheckLogin
    public ApiResult<SysUser> getCurrentUser() {
        return ApiResult.success(userService.getCurrentUser());
    }

    @PostMapping("/password")
    @ApiOperation("修改密码")
    @SaCheckLogin
    public ApiResult<Void> updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
        userService.updatePassword(oldPassword, newPassword);
        return ApiResult.success();
    }

    @GetMapping("/page")
    @ApiOperation("分页查询用户")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Page<SysUser>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String realName) {
        
        Page<SysUser> page = userService.page(
                new Page<>(current, size),
                new LambdaQueryWrapper<SysUser>()
                        .like(username != null, SysUser::getUsername, username)
                        .like(realName != null, SysUser::getRealName, realName)
                        .orderByDesc(SysUser::getCreatedTime)
        );
        
        return ApiResult.success(page);
    }

    @PostMapping
    @ApiOperation("新增用户")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> add(@Validated @RequestBody SysUser user) {
        userService.register(user);
        return ApiResult.success();
    }

    @PutMapping
    @ApiOperation("修改用户")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> update(@Validated @RequestBody SysUser user) {
        user.setPassword(null); // 不允许修改密码
        userService.updateById(user);
        return ApiResult.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> delete(@PathVariable Long id) {
        userService.removeById(id);
        return ApiResult.success();
    }
} 